import pickle,base64
from django_redis import get_redis_connection
from django import http


def merge_cart_cookie_to_redis(request, user, response):
    cart_str = request.COOKIES.get('carts')
    if not cart_str:
        return None
    cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
# {
#     '<sku_id>': {
#         'count': '<count>',
#         'selected': '<selected>',
#     },
#     ...
# }
    new_cart_dict = {}
    new_add_selected = []
    new_remove_selected = []
    for sku_id, item in cart_dict.items():
        new_cart_dict[sku_id] = item['count']
        if item['selected']:
            new_add_selected.append(sku_id)
        else:
            new_remove_selected.append(sku_id)

    user_id = user.id
    redis_conn = get_redis_connection('carts')
    pl = redis_conn.pipeline()
    pl.hmset('carts_%s' % user_id, new_cart_dict)
    if new_add_selected:
        pl.sadd('selected_%s' % user_id, *new_add_selected)
    if new_remove_selected:
        pl.srem('selected_%s' % user_id, *new_remove_selected)
    pl.execute()

    response.delete_cookie('carts')
    return response